package net.jmcoding.admin.be;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import net.jmcoding.core.JMCoding;
import net.jmcoding.core.service.impl.AbstractCompInvoker;

@Service("LOGIN_CHECK_SERVICE")
public class LoginCheckService implements net.jmcoding.core.ext.ILoginCheck {
    private final static Logger logger = LoggerFactory.getLogger(LoginCheckService.class);
    
    @Autowired
    private RedisTemplate redisTemplate;
    
    @Override
    public boolean check(String functionCode, HttpServletRequest request) {
        // TODO Auto-generated method stub

        String ticket = request.getHeader("Token");
        if(ticket == null) {
            logger.info("访问者无ticket");
            // 访问缺失token
            return false;
        }
        
        // 访问指定服务，校验token的有效性
        java.util.HashMap parm = new java.util.HashMap();
        parm.put("ticket", ticket);
        java.util.Map checkResult = JMCoding.call("/sec/check/ticket", parm, request , null);
        
        // 调用过程出现异常
        if(checkResult == null) {
            logger.info("执行引擎调用异常");
            return false;
        }
        
        boolean isSuccess = (boolean)checkResult.get("success");
        
        if(!isSuccess) {
            logger.debug(checkResult.get("code").toString());
            logger.debug(checkResult.get("msg").toString());
        }
        
        return isSuccess;
    }

    @Override
    public Object getUserInfo(String functionCode, HttpServletRequest request) {
        // TODO 从Redis中获取缓存的用户信息
        
        String ticket = request.getHeader("Token");
        String key = "user-" + ticket;
        
        ValueOperations ops = redisTemplate.opsForValue();
        
        if( redisTemplate.hasKey(key) ) {
            java.util.Map cacheMap = (Map)ops.get(key);
            
            return cacheMap;
        }
        
        return null;
        
    }

}
